package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.zbkj.common.model.admin.SystemAdmin;
import com.zbkj.common.model.agent.BrandAgentRegion;
import com.zbkj.common.model.agent.UserAgent;
import com.zbkj.common.model.coupon.Coupon;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.*;
import com.github.pagehelper.PageHelper;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zbkj.common.exception.AppException;

import com.zbkj.common.response.*;
import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.model.agent.CommunityBrokerage;
import com.zbkj.common.utils.SecurityUtil;
import com.zbkj.common.vo.LoginUserVo;
import com.zbkj.service.dao.CommunityBrokerageDao;
import com.zbkj.service.service.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.service.util.BrandUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author Caiyc
* @description CommunityBrokerageServiceImpl 接口实现
* @date 2025-07-21
*/
@Service
public class CommunityBrokerageServiceImpl extends ServiceImpl<CommunityBrokerageDao, CommunityBrokerage> implements CommunityBrokerageService {

    @Resource
    private CommunityBrokerageDao dao;
    @Autowired
    private BrandAgentRegionService brandAgentRegionService;
    @Autowired
    private UserService userService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private UserAgentService userAgentService;
    @Autowired
    private AgentCategoryService agentCategoryService;


    @Override
    public Boolean create(CommunityBrokerageSaveRequest communityBrokerageSaveRequest) {
        LoginUserVo loginUserVo = SecurityUtil.getLoginUserVo();

        CommunityBrokerage communityBrokerage = new CommunityBrokerage();
        BeanUtils.copyProperties(communityBrokerageSaveRequest, communityBrokerage, "id");

        BrandAgentRegion brandAgentRegion = brandAgentRegionService.getById(communityBrokerageSaveRequest.getAgentRegionId());
        communityBrokerage.setLongitude(brandAgentRegion.getLongitude());
        communityBrokerage.setLatitude(brandAgentRegion.getLatitude());
        communityBrokerage.setIsCanSelect(true);
        communityBrokerage.setSystemAdminId(loginUserVo.getUser().getId());
        communityBrokerage.setBrandId(BrandUtil.getBrandIdByUrl());
        boolean save = save(communityBrokerage);
        if (!save) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "添加失败");
        }
        return save;
    }

    /**
     * 分页查询小区分佣设置表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<CommunityBrokerage>
     * @author Caiyc
     * @since 2025-07-21
     */
    @Override
    public List<MerchantBrokeragePageDataResponse> getList(MerchantBrokerageSearchRequest request, PageParamRequest pageParamRequest) {
        SystemAdmin currentUser = SecurityUtil.getLoginUserVo().getUser();

        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        //带 CommunityBrokerage 类的多条件查询
        LambdaQueryWrapper<CommunityBrokerage> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(CommunityBrokerage::getBrandId, BrandUtil.getBrandIdByUrl());
        lambdaQueryWrapper.eq(CommunityBrokerage::getIsDel, false);
        lambdaQueryWrapper.eq(CommunityBrokerage::getType, 0);
        lambdaQueryWrapper.eq(CommunityBrokerage::getSystemAdminId, currentUser.getId());

        lambdaQueryWrapper.orderByDesc(CommunityBrokerage::getCreateTime);
        List<CommunityBrokerage> communityBrokerages = dao.selectList(lambdaQueryWrapper);
        // 添加活动状态
        List<MerchantBrokeragePageDataResponse> communityBrokerageResponses = new ArrayList<>();

        communityBrokerages.stream().forEach(x->{
            MerchantBrokeragePageDataResponse communityBrokerageResponse = new MerchantBrokeragePageDataResponse();
            BeanUtils.copyProperties(x, communityBrokerageResponse);
            // 商户名称
            String name = merchantService.getNameById(x.getMerId());
            communityBrokerageResponse.setMerchantName(name);
            // 分类处理
            if(StrUtil.isNotBlank(x.getCategoryItems())){
                List<String> list = new ArrayList<>();
                String[] split = x.getCategoryItems().split(",");
                for (String s : split) {
                    String[] split1 = s.split("\\:");
                    Integer id = Integer.parseInt(split1[0]);
                    String s1 = getName(id) + ":" + split1[1];
                    list.add(s1);
                }
                if (CollUtil.isNotEmpty(list)){
                    communityBrokerageResponse.setCategoryItemsName(StrUtil.join(",", list));
                }
            }
            communityBrokerageResponses.add(communityBrokerageResponse);
        });
        return communityBrokerageResponses;
    }

    private String getName(Integer id) {
//        AgentCategory agentCategory = agentCategoryService.getById(agentConfigCategoryRequest.getCategoryId());
//        id
        return "";
    }

    /**
    * 修改小区分佣设置表
    * @param request
    * @return
    */
    @Override
    public boolean update(CommunityBrokerageSaveRequest request) {
        CommunityBrokerage communityBrokerage = getByRegionId(request.getAgentRegionId());
        if (ObjectUtil.isNull(communityBrokerage)) {
            communityBrokerage = new CommunityBrokerage();
            LoginUserVo loginUserVo = SecurityUtil.getLoginUserVo();

            communityBrokerage.setIsCanSelect(true);
            communityBrokerage.setSystemAdminId(loginUserVo.getUser().getId());
            communityBrokerage.setBrandId(BrandUtil.getBrandIdByUrl());
        }
        BeanUtils.copyProperties(request, communityBrokerage, "id");

        BrandAgentRegion brandAgentRegion = brandAgentRegionService.getById(request.getAgentRegionId());
        communityBrokerage.setLongitude(brandAgentRegion.getLongitude());
        communityBrokerage.setLatitude(brandAgentRegion.getLatitude());
        communityBrokerage.setUpdateTime(new Date());
        boolean update = saveOrUpdate(communityBrokerage);
        if (!update) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "更新失败");
        }
        return update;
    }

    private CommunityBrokerage getByRegionId(Integer agentRegionId) {
        LambdaQueryWrapper<CommunityBrokerage> lqw = Wrappers.lambdaQuery();
        lqw.eq(CommunityBrokerage::getIsDel, 0);
        lqw.eq(CommunityBrokerage::getAgentRegionId, agentRegionId);
        lqw.last("limit 1");
        CommunityBrokerage communityBrokerage = this.getOne(lqw);
        return communityBrokerage;
    }

    private CommunityBrokerage getByRegionId(Integer agentRegionId, Integer merId) {
        LambdaQueryWrapper<CommunityBrokerage> lqw = Wrappers.lambdaQuery();
        lqw.eq(CommunityBrokerage::getIsDel, 0);
        if (ObjectUtil.isNotNull(agentRegionId)) {
            lqw.eq(CommunityBrokerage::getAgentRegionId, agentRegionId);
        }
        if (ObjectUtil.isNotNull(merId)) {
            lqw.eq(CommunityBrokerage::getMerId, merId);
        }
        lqw.last("limit 1");
        CommunityBrokerage communityBrokerage = this.getOne(lqw);
        return communityBrokerage;
    }

    private CommunityBrokerage getByIdException(Integer id) {
        CommunityBrokerage communityBrokerage = getById(id);
        if (ObjectUtil.isNull(communityBrokerage)) {
            throw new AppException("分佣设置不存在");
        }
        if (communityBrokerage.getIsDel()) {
            throw new AppException("分佣设置不存在");
        }
        return communityBrokerage;
    }

    /**
    * 批量删除
    * @param idList
    * @return
    */
    @Override
    public boolean batchDelete(List<Integer> idList) {
        LambdaUpdateWrapper<CommunityBrokerage> luw = Wrappers.lambdaUpdate();
        luw.set(CommunityBrokerage::getIsDel, true);
        luw.in(CommunityBrokerage::getId, idList);
        boolean update = update(luw);
        if (!update) {
            throw new AppException(CommonResultCode.ERROR.setMessage("批量删除小区分佣设置表失败"));
        }
        return true;
    }

    /**
    * 查询详情
    * @param agentRegionId
    * @return
    */
    @Override
    public CommunityBrokerageDetailResponse getDetails(Integer agentRegionId) {
        LambdaQueryWrapper<CommunityBrokerage> lqw = Wrappers.lambdaQuery();
        lqw.eq(CommunityBrokerage::getIsDel, 0);
        lqw.eq(CommunityBrokerage::getAgentRegionId, agentRegionId);
        lqw.last("limit 1");
        CommunityBrokerage communityBrokerage = this.getOne(lqw);
        if (ObjectUtil.isNotNull(communityBrokerage)) {
            CommunityBrokerageDetailResponse response = new CommunityBrokerageDetailResponse();
            BeanUtils.copyProperties(communityBrokerage, response);
            return response;
        }
        return null;
    }

    /**
    * 查询详情
    * @param id
    * @return
    */
    @Override
    public MerchantBrokerageDetailResponse getDetailsByMerchant(Integer id) {
        LambdaQueryWrapper<CommunityBrokerage> lqw = Wrappers.lambdaQuery();
        lqw.eq(CommunityBrokerage::getIsDel, 0);
        lqw.eq(CommunityBrokerage::getId, id);
        lqw.last("limit 1");
        CommunityBrokerage communityBrokerage = this.getOne(lqw);
        if (ObjectUtil.isNotNull(communityBrokerage)) {
            MerchantBrokerageDetailResponse response = new MerchantBrokerageDetailResponse();
            BeanUtils.copyProperties(communityBrokerage, response);
            return response;
        }
        return null;
    }

    /**
     * 通过经纬度查询小区列表
     * @param request
     * @return
     */
    @Override
    public List<CommunityListResponse> getCommunityList(CommunityListParamRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put("latitude", request.getLatitude());
        map.put("longitude", request.getLongitude());
        List<CommunityBrokerage> list = this.dao.selectListSql(map);
        if (CollUtil.isNotEmpty(list)) {
            return list.stream().map(x -> {
                CommunityListResponse response = new CommunityListResponse();
                BeanUtils.copyProperties(x, response);
                return response;
            }).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public MerchantBrokerageConfigInfoResponse getInfo(SystemAdmin systemAdmin, Integer id) {
        LambdaQueryWrapper<CommunityBrokerage> lqw = Wrappers.lambdaQuery();
        lqw.eq(CommunityBrokerage::getIsDel, 0);
        lqw.eq(CommunityBrokerage::getType, 1);
        lqw.eq(CommunityBrokerage::getId, id);
        lqw.eq(CommunityBrokerage::getMerId, systemAdmin.getMerId());
        CommunityBrokerage communityBrokerage = this.getOne(lqw);
        if (ObjectUtil.isNull(communityBrokerage)) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "未查询到分红设置");
        }
        MerchantBrokerageConfigInfoResponse response = new MerchantBrokerageConfigInfoResponse();
        BeanUtils.copyProperties(communityBrokerage, response);
        return response;
    }

    @Override
    public boolean updateConfig(MerchantBrokerageConfigInfoRequest request, SystemAdmin systemAdmin) {
        CommunityBrokerage communityBrokerage = null;
        if(ObjectUtil.isNotNull(request.getId())){
            LambdaQueryWrapper<CommunityBrokerage> lqw = Wrappers.lambdaQuery();
            lqw.eq(CommunityBrokerage::getIsDel, 0);
            lqw.eq(CommunityBrokerage::getType, 1);
            lqw.eq(CommunityBrokerage::getId, request.getId());
            lqw.eq(CommunityBrokerage::getMerId, systemAdmin.getMerId());
            lqw.last("limit 1");
            communityBrokerage = this.getOne(lqw);
            if (ObjectUtil.isNull(communityBrokerage)) {
                throw new AppException(CommonResultCode.VALIDATE_FAILED, "未查询到分红设置");
            }
        }

        if (ObjectUtil.isNull(communityBrokerage)) {
            communityBrokerage = new CommunityBrokerage();
            communityBrokerage.setIsCanSelect(true);
            communityBrokerage.setBrandId(BrandUtil.getBrandIdByUrl());
            communityBrokerage.setMerId(systemAdmin.getMerId());
            communityBrokerage.setType(1);
        }
        BeanUtils.copyProperties(request, communityBrokerage);

        communityBrokerage.setUpdateTime(new Date());
        boolean update = saveOrUpdate(communityBrokerage);
        if (!update) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "更新失败");
        }
        return update;
    }

    @Override
    public CommunityBrokerage getByMerId(Integer merId) {
        LambdaQueryWrapper<CommunityBrokerage> lqw = Wrappers.lambdaQuery();
        lqw.eq(CommunityBrokerage::getIsDel, 0);
        lqw.eq(CommunityBrokerage::getStatus, 1);
        lqw.eq(CommunityBrokerage::getAgentRegionId, 0);
        lqw.eq(CommunityBrokerage::getMerId, merId);
        lqw.last("limit 1");
        return this.getOne(lqw);
    }

    @Override
    public List<CommunityBrokerage> getCommunityList() {
        LambdaQueryWrapper<CommunityBrokerage> lqw = Wrappers.lambdaQuery();
        lqw.eq(CommunityBrokerage::getIsDel, 0);
        lqw.ne(CommunityBrokerage::getAgentRegionId, 0);
        lqw.eq(CommunityBrokerage::getStatus, 1);
        lqw.eq(CommunityBrokerage::getMerId, 0);
        return this.list(lqw);
    }

    @Override
    public PageInfo<MerchantBrokerageConfigPageDataResponse> getListMerchant(MerchantBrokerageConfigSearchRequest request, PageParamRequest pageParamRequest) {
        SystemAdmin systemAdmin = userService.getSystemAdminByMerchantEmployee();

        Page<Coupon> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<CommunityBrokerage> lqw = new LambdaQueryWrapper<>();
        lqw.eq(CommunityBrokerage::getMerId, systemAdmin.getMerId());
        lqw.eq(CommunityBrokerage::getIsDel, false);

        lqw.orderByDesc(CommunityBrokerage::getCreateTime);
        List<CommunityBrokerage> couponList = dao.selectList(lqw);
        List<MerchantBrokerageConfigPageDataResponse> shortplayItemsResponses = new ArrayList<>();
        couponList.stream().forEach(items -> {
            MerchantBrokerageConfigPageDataResponse shortplayItemsResponse = new MerchantBrokerageConfigPageDataResponse();
            BeanUtils.copyProperties(items, shortplayItemsResponse);
            shortplayItemsResponses.add(shortplayItemsResponse);
        });
        return CommonPage.copyPageInfo(page, shortplayItemsResponses);
    }

    @Override
    public boolean delete(Integer id) {
        SystemAdmin systemAdmin = userService.getSystemAdminByMerchantEmployee();
        CommunityBrokerage communityBrokerage = getByIdException(id);
        if (!systemAdmin.getMerId().equals(communityBrokerage.getMerId())) {
            throw new AppException("不允许删除");
        }
        LambdaUpdateWrapper<CommunityBrokerage> wrapper = Wrappers.lambdaUpdate();
        wrapper.set(CommunityBrokerage::getIsDel, 1);
        wrapper.eq(CommunityBrokerage::getId, id);
        return update(wrapper);
    }

    /**
     * 查询最新一个启用状态的商户分红设置
     * @param merId
     * @param brandId
     * @return
     */
    @Override
    public CommunityBrokerage getLatestConfig(Integer merId, Integer brandId) {
        LambdaQueryWrapper<CommunityBrokerage> lqw = Wrappers.lambdaQuery();
        lqw.eq(CommunityBrokerage::getIsDel, 0);
        lqw.eq(CommunityBrokerage::getType, 1);
        lqw.eq(CommunityBrokerage::getStatus, 1);
        lqw.eq(CommunityBrokerage::getBrandId, brandId);
        lqw.eq(CommunityBrokerage::getMerId, merId);
        lqw.orderByDesc(CommunityBrokerage::getCreateTime);
        lqw.last("limit 1");
        return this.getOne(lqw);
    }

    @Override
    public CommunityBrokerage getLatestConfigByCommunity(Integer communityId) {
        LambdaQueryWrapper<CommunityBrokerage> lqw = Wrappers.lambdaQuery();
        lqw.eq(CommunityBrokerage::getIsDel, 0);
        lqw.eq(CommunityBrokerage::getType, 0);
        lqw.eq(CommunityBrokerage::getStatus, 1);
        lqw.eq(CommunityBrokerage::getId, communityId);
        return this.getOne(lqw);
    }

    @Override
    public CommunityBrokerage getMerchantBrokerageRate(Integer merId) {
        LambdaQueryWrapper<CommunityBrokerage> lqw = Wrappers.lambdaQuery();
        lqw.eq(CommunityBrokerage::getIsDel, 0);
        lqw.eq(CommunityBrokerage::getType, 0);
        lqw.eq(CommunityBrokerage::getMerId, merId);
        lqw.last("limit 1");
        CommunityBrokerage communityBrokerage = this.getOne(lqw);
        return communityBrokerage;
    }

    @Override
    public boolean updateByMerchant(MerchantBrokerageSaveRequest request) {
        SystemAdmin currentUser = SecurityUtil.getLoginUserVo().getUser();
        List<UserAgent> userAgentList = userAgentService.getListByAdminId(currentUser.getId());
        if (CollUtil.isNotEmpty(userAgentList)) {
            userAgentList.get(0);
        }

        CommunityBrokerage communityBrokerage = getByAdminId(currentUser.getId(), request.getMerId());
        if (request.getId() == null || request.getId() == 0) {
            CommunityBrokerage communityBrokerageTmp = getByAdminId(currentUser.getId(), request.getMerId());
            if (ObjectUtil.isNotNull(communityBrokerageTmp)) {
                throw new AppException(CommonResultCode.VALIDATE_FAILED, "请不要重复添加");
            }
        }
        if (ObjectUtil.isNull(communityBrokerage)) {
            communityBrokerage = new CommunityBrokerage();
            LoginUserVo loginUserVo = SecurityUtil.getLoginUserVo();

            communityBrokerage.setIsCanSelect(true);
            communityBrokerage.setSystemAdminId(loginUserVo.getUser().getId());
            communityBrokerage.setBrandId(BrandUtil.getBrandIdByUrl());
            communityBrokerage.setType(0);
        }
        BeanUtils.copyProperties(request, communityBrokerage, "id");
        communityBrokerage.setUpdateTime(new Date());
        boolean update = saveOrUpdate(communityBrokerage);
        if (!update) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "更新失败");
        }
        return update;
    }

    private CommunityBrokerage getByAdminId(Integer id, Integer merId) {
        LambdaQueryWrapper<CommunityBrokerage> lqw = Wrappers.lambdaQuery();
        lqw.eq(CommunityBrokerage::getIsDel, 0);
        lqw.eq(CommunityBrokerage::getSystemAdminId, id);
        lqw.eq(CommunityBrokerage::getMerId, merId);
        lqw.last("limit 1");
        CommunityBrokerage communityBrokerage = this.getOne(lqw);
        return communityBrokerage;
    }

}

